#include <public/globalsensor_tc_store_test.h>
#include <public/PackMemManager.h>
#include <public/sgi_link_layer.h>
#include <public/ssi_link_layer.h>
#include <public/basic_types.h>
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <cstring>


using namespace std;

#define PACK_BYTES_FOR_STORING_TM_FRAMES 253
#define TM_FRAME_HEADER_AND_CRC_SIZE 18
#define TM_FRAME_HEADER_SIZE 16
#define MAX_BYTES_FROM_FILE 30

uint64_t fileSize( const char* filePath ){

	uint64_t fsize = 0;
	ifstream file(filePath, ios::binary);

	fsize = file.tellg();
	file.seekg( 0, std::ios::end );
	fsize = (uint64_t)file.tellg() - fsize;
	file.close();

	return fsize;
}
bool CTestSGI_SensorTC::buildPack(CPackHandler &pack){
	//compruebo que hay al menos un archivo m_files que no se ha leido entero.
	//Es decir que exite un i < 6 para el que m_filePendingBytes[i] es distinto de cero.
	//uso el rand de 0 a 5, (o sea rand %6) para elegir un índice
	byte_t nextFrameBytes;
    ofstream file_salida ("./test_files/mipaquete.txt",ios::binary);
	while (m_filePendingBytes[0]+m_filePendingBytes[1]>0){
		int i=rand()%2;
		if(m_filePendingBytes[i]>0){
		cout<<m_fileNames[i]<<endl;
		ifstream file(m_fileNames[i], ios::binary);
		cout<<m_filePendingBytes[i]<<endl;
		file.seekg((size[i]-m_filePendingBytes[i]), ios::beg);
		if (m_filePendingBytes[i]!=0){
			sgi_link_layer_sen_tc_frame_t frame;
			int16_t FRAME=4;
			if (m_filePendingBytes[i]<6){
				nextFrameBytes = m_filePendingBytes[i];
			}else{
			nextFrameBytes = rand()%6;
			}
			frame.sensor_id= FRAME;
			frame.length=nextFrameBytes;
			for (int x=0;x<frame.length;x++){
				byte_t aux;
				aux=file.get();
				frame.data[x]=aux;
				cout<<aux<<endl;
			}
			pack.WriteByte(index,frame.sensor_id);
			index++;
			pack.WriteByte(index,frame.length);
			index++;
			for (int z=0;z<frame.length;z++){
				pack.WriteByte(index,frame.data[z]);
				index++;
				file_salida.put(frame.data[z]);
			}

			m_filePendingBytes[i]-=nextFrameBytes;
		}
		file.close();
	}
	}
	return 0;
}
